/*
    表单验证及提交
 */
var $phone = $("#loginPhone");
var $pwd = $("#loginPassword1");
var $pwdText = $("#loginPassword2");
var $eyeOpen = $(".js-eye-open");

var $registerPhone = $("#registerPhone");
var $registerCode = $("#registerCode");
var $registerPassword1 = $("#registerPassword1");
var $registerPassword2 = $("#registerPassword2");

var flagphone = false;//公共flag 判断是不是验证通过
var flagpwd = false;//公共flag 判断是不是验证通过
var flagpwdText = false;//公共flag 判断是不是验证通过
var flagregisterPhone = false;//公共flag 判断是不是验证通过
var flagregisterCode = false;//公共flag 判断是不是验证通过
var flagregisterPassword1 = false;//公共flag 判断是不是验证通过
var flagregisterPassword2 = false;//公共flag 判断是不是验证通过

(function(){
  var phoneReg = /^[1][0-9]{10}$/; //手机号正则
  var pwdReg = /^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,22}$/; //密码正则
  var codeReg = /^[0-9]{4}$/; //验证码正则
  var wait = 60; //发送验证码等待时间

  //查看明文密码
  $eyeOpen.on("click", lookPwd);

  //提交事件
  $("#loginBtn").on("click", loginSubmit);
  $("#registerBtn").on("click", registerSubmit);

  //切换选项卡
  $("#nav_register").on("click", "li", function(){
       var index = $(this).index();

       $(this).addClass("active").siblings().removeClass("active");
       $("#form_register").find(".js-form").eq(index).show().siblings().hide();
  });

  if($("#toRegisterFlag").val()=='true'){
    $("#toRegister").click();
  }

  //手机号输入框事件
  $phone.on("onreadystatechange input blur", function(){
      var $this = $(this);
      var phone = $this.val();

      flagphone = validateForm($this, phone, phoneReg, "请输入正确的手机号");
  });

  //密码输入框事件
  $pwd.on("onreadystatechange input blur", function(){
      var $this = $(this);
      var $cleartext = $this.next("input[type='text']");
      var pwd = $this.val();

      $cleartext.val(pwd);

      flagpwd = validateForm($this, pwd, pwdReg, "请输入正确的密码", $cleartext);
  });

  //明文密码输入框事件
  $pwdText.on("onreadystatechange input blur", function(){
      var $this = $(this);
      var $cleartext = $this.prev("input[type='password']");
      var pwd = $this.val();

      $cleartext.val(pwd);

      flagpwdText = validateForm($this, pwd, pwdReg, "请输入正确的密码", $cleartext);
  });

  //手机号输入框事件
  $registerPhone.on("onreadystatechange input blur", function(){
      var $this = $(this);
      var registerPhone = $this.val();

      flagregisterPhone = validateForm($this, registerPhone, phoneReg, "请输入正确的手机号");
  });

  //验证码输入框事件
  $registerCode.on("onreadystatechange input blur", function(){
      var $this = $(this);
      var $cleartext = $this.next("input[type='text']");
      var registerCode = $this.val();

      flagregisterCode = validateForm($this, registerCode, codeReg, "请输入正确的验证码", $cleartext);
  });

  //密码输入框事件
  $registerPassword1.on("onreadystatechange input blur", function(){
      var $this = $(this);
      var $cleartext = $this.next("input[type='text']");
      var registerPassword = $this.val();

      $cleartext.val(registerPassword);

      flagregisterPassword1 = validateForm($this, registerPassword, pwdReg, "请输入正确的密码", $cleartext);
  });
  //明文密码输入框事件
  $registerPassword2.on("onreadystatechange input blur", function(){
      var $this = $(this);
      var $cleartext = $this.prev("input[type='password']");
      var registerPassword = $this.val();

      $cleartext.val(registerPassword);

      flagregisterPassword2 = validateForm($this, registerPassword, pwdReg, "请输入正确的密码", $cleartext);
  });

  //表单验证, 前面四个都是必传参数：当前输入框、当前值、正则、提示文字，最后一个参数是可选参数：查看明文密码
  function validateForm(that, value, reg, txt, cleartext){
      var $parent = that.closest(".form-group");
      var $addon = $parent.find(".input-group-addon");
      var $msg = $parent.find(".js-line-alert");
      var $msgText = $parent.find(".js-alert-text");
      
      var flag = true;

      if(value.length === 0){
        modifyWarning($msgText, txt);
        showWarning($addon, that, $msg, cleartext);
        flag = false;
      }
      else if(!reg.test(value)){
        modifyWarning($msgText, txt);
        showWarning($addon, that, $msg, cleartext);
        flag = false;
      }
      else{
        hideWarning($addon, that, $msg, cleartext);
      }

      return flag;
  }

  //输入框边框变红并显示提示文字
  function showWarning(addon, input, msg, cleartext){
    if(cleartext){
      cleartext.addClass("input-error border-error");
    }
    addon.addClass("border-error");
    input.addClass("input-error border-error");
    msg.show();
  }

  //输入框边框恢复原色并隐藏提示文字
  function hideWarning(addon, input, msg, cleartext){
    if(cleartext){
      cleartext.removeClass("input-error border-error");
    }
    addon.removeClass("border-error");
    input.removeClass("input-error border-error");
    msg.hide();
  }

  //修改提示文字信息
  function modifyWarning(element, txt){
    element.text(txt);
  }

  //查看明文密码
  function lookPwd(){
    var $pwd = $(this).closest(".input-group").find("input[type='password']");
    var $pwd_show = $pwd.next("input[type='text']");
    var pwd = $pwd.val();
    var pwd_show = $pwd_show.val();

    if($pwd.is(":visible")){
        $pwd.hide();
        $pwd_show.val(pwd).show();
    }
    else{
        $pwd.val(pwd_show).show();
        $pwd_show.hide();
    }
  }

  //表单登录提交
  function loginSubmit(){

    var loginPhone = $phone.val();
    var loginPassword = $pwd.val();

    $phone.blur();
    $pwd.blur();
    $pwdText.blur();

    if(flagphone && flagpwd && flagpwdText){
      $.ajax({
        url: "login",
        type: "post",
        dataType: 'json',
        data : {
          phone: loginPhone,
          pwd: loginPassword
        },
        success: function(data) {
          if (data.returnFlag == '0') {
            location.href = $('#returnPath').val() + $("#returnPage").val();
          }else {
            if (data.returnCode == 'A001') {
                layer.open({
                    content: '您的密码有误!',
                    scrollbar: false
                });
            }else if (data.returnCode == 'A002') {
                layer.open({
                    content: '无此用户!',
                    scrollbar: false
                });
            }else {
                layer.open({
                    content: '操作失败!',
                    scrollbar: false
                });
            }
          }
        },
        error: function(xhr, type, errorThrown) {
          //异常处理
          //validateFormShow("请稍后再试!");
          modifyWarning($msgText, "请稍后再试!");
          showWarning($addon, that, $msg, cleartext);
        }
      });
    }
  }

  //注册
  function registerSubmit(){
    var phone = $('#registerPhone').val();
    var pwd = $('#registerPassword1').val();
    var token = $('#registerCode').val();

    $registerPhone.blur();
    $registerCode.blur();
    $registerPassword1.blur();
    $registerPassword2.blur();

    var hasChk = $('#agreement').is(':checked');
		if(hasChk){
		    /*已选中*/
		}else{
		    /*未选中*/
            layer.open({
                content: '没勾选楚才用户协议!',
                scrollbar: false
            });
		    return false;
		}

    if(flagregisterPhone && flagregisterCode && flagregisterPassword1 && flagregisterPassword2){
      $.ajax({
        url: "register",
        type: "post",
        dataType: 'json',
        data : {
          phone : phone,
          pwd : pwd,
          token :token
        },
        success: function(data) {
          if (data.returnFlag == '0') {
            location.href = "../user/loginPage";
          }
                  else {
          if (data.returnCode == "A001") {
              layer.open({
                  content: '您的帐号已存在!',
                  scrollbar: false
              });
            }
          else{
              layer.open({
                  content: '您的验证码错误!',
                  scrollbar: false
              });
          }
          }
        },
        error: function(xhr, type, errorThrown) {
          //异常处理；
        alert("请稍后再试!");
        }
      });
    }
  }

  var captchaBtn = document.getElementById("captchaBtn");

  captchaBtn.addEventListener("click", function() {
    var $this = $(this);
    var phone = $("#registerPhone").val();

    var flag = validateForm($registerPhone, phone, phoneReg, "请输入正确的手机号");

    if (flag) {
      sendCode(captchaBtn);
      timeChange(captchaBtn);
    } else {
      return false;
    }
  });
    
  //验证码时间改变
  function timeChange(btn) {
    if (wait === 0) {
      $(btn).removeClass("c-red");
      btn.removeAttribute("disabled");
      btn.innerText = "发送验证码";
      wait = 60;
    } else {
      $(btn).addClass("c-red");
      btn.setAttribute("disabled", true);
      btn.innerText = "(" + wait + ")秒后重新获取";
      wait--;
      setTimeout(function(){
        timeChange(btn);
      }, 1000);
    }
  }
    
  //发送验证码
  function sendCode(btn) {
    var phone = $("#registerPhone").val();

    if (btn.innerText == "发送验证码") {
      $.ajax({
        url: "../apptoken/sendToken",
        type: "get",
        data: {
          phone : phone
        },
        dataType: 'json',
        success: function(data) {
          if (data.returnFlag != 0) {
            flagregisterPhone = validateForm($this, phone, phoneReg, "请输入正确的手机号");
          }
        },
        error: function(xhr, type, errorThrown) {
          //异常处理；
          flagregisterPhone = validateForm($this, phone, phoneReg, "请稍后在试！");
        }
      });
    } else {
      return false;
    }
  }

})();